package com.yubest.springboothello.service.impl;

import com.yubest.springboothello.dto.UserDto;
import com.yubest.springboothello.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: hweiyu
 * @Date: 2023/4/13 9:19
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    private static final Map<Long, UserDto> CACHE_MAP = new ConcurrentHashMap<>();

    @Override
    @Cacheable(value = "userCache", key = "#userId")
    public UserDto getById(Long userId) {
        log.info("getById: {}", userId);
        return CACHE_MAP.get(userId);
    }

    @Override
    @CachePut(value = "userCache", key = "#user.id")
    public void saveOrUpdate(UserDto user) {
        log.info("saveOrUpdate: {}", user.getId());
        CACHE_MAP.put(user.getId(), user);
    }

    @Override
    @CacheEvict(value = "userCache", key = "#userId")
    public void deleteById(Long userId) {
        log.info("deleteById: {}", userId);
        CACHE_MAP.remove(userId);
    }
}
